package club.jdiy.admin.interceptor;

import club.jdiy.admin.SystemConfig;
import club.jdiy.admin.entity.Menu;
import club.jdiy.core.AdminContext;
import club.jdiy.core.AppContext;
import club.jdiy.admin.entity.User;
import club.jdiy.admin.service.UserService;
import club.jdiy.core.properties.JDiyProperties;
import club.jdiy.dev.controller.JDiyController;
import club.jdiy.dev.view.FtlInvoker;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JDiyAdminInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object obj) throws Exception {
        User user = null;
        try {
            user = userService.findById(Integer.parseInt(context.getCookie("userId"))).orElse(null);
        } catch (Exception ignore) {
        }
        String userToken = context.getCookie("userToken");
        if (user == null || Boolean.TRUE.equals(user.getRemoved()) || !user.token(context.getConfig(SystemConfig.class).isSingleLoginOn()).equals(userToken)) {
            context.setCookie("userId,userToken", null);
            if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")) || request.getParameter("ajax") != null) {
                response.setCharacterEncoding("utf-8");
                response.setHeader("Content-Type", "application/json; charset=utf-8");
                response.setContentType("application/json; charset=utf-8");
                response.setHeader("mgmtTimeout", "yes");
                response.getWriter().println("{\"code\":\"301\", \"msg\":\"会话超时\"}");
            } else {
                String uri = request.getRequestURI();
                if ("/mgmt".equals(uri) || "/mgmt/".equals(uri)) {
                    request.getRequestDispatcher("/mgmt/login").forward(request, response);
                } else {
                    response.sendRedirect(context.getContextPathURL() + "/mgmt/login?s=timeout");
                }
            }
            return false;
        } else {
            request.setAttribute("CURRENT_USER", user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object arg2, ModelAndView view) throws IOException, TemplateException {
        if (view != null && !view.isEmpty()) {
            view.getModelMap().put("_", "" + System.currentTimeMillis());

            if ((request.getRequestURI().equals("/mgmt") || request.getRequestURI().equals("/mgmt/"))
                    && adminContext.isDeveloper()) {
                List<Menu> children = new ArrayList<>();
                children.add(new Menu("界面配置", request.getContextPath() + "/mgmt/JDiyAdmin/ui.list"));
                children.add(new Menu("菜单配置", request.getContextPath() + "/mgmt/JDiyAdmin/menu.list"));
                children.add(new Menu("字典配置", request.getContextPath() + "/mgmt/JDiyAdmin/dict.list"));
                children.add(new Menu("实体管理", request.getContextPath() + "/mgmt/JDiyAdmin/entity.list"));
                children.add(new Menu("定时任务管理", request.getContextPath() + "/mgmt/JDiy/zlt/list.tab.sys_jobls"));
                children.add(new Menu("系统设置", request.getContextPath() + "/mgmt/JDiyAdmin/etc.settings"));
                children.add(new Menu("数据库文档导出", request.getContextPath() + "/mgmt/JDiyAdmin/etc.dbDict"));
                children.add(new Menu("API开发(内测)", request.getContextPath() + "/mgmt/JDiyAdmin/etc.api"));

                Menu root = new Menu();
                root.setName("在线开发");
                root.setChildren(children);

                List<Menu> roots = new ArrayList<>();
                roots.add(root);
                view.getModelMap().put("topMenu", roots);

            }

            if (arg2 instanceof HandlerMethod) {
                HandlerMethod hm = (HandlerMethod) arg2;
                Class<?> clazz = hm.getBeanType();
                if (JDiyController.class.isAssignableFrom(clazz)) {
                    String s = view.getViewName();
                    if (s != null && s.startsWith("mgmt/JDiyAdmin/")) s = s.substring(15);
                    response.setContentType("text/html;charset=utf-8");
                    ftlInvoker.invoke(s, response, view.getModelMap());
                    view.clear();
                }
            }
        }
    }
    @Resource
    private AdminContext adminContext;
    @Resource
    private UserService userService;
    @Resource
    private AppContext context;
    @Resource
    private FtlInvoker ftlInvoker;
}